package com.wanmao.test;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wanmao.test.framgent.Framgent_Test_Search;
import com.wanmao.test.framgent.Framgent_Test_Task;
import com.wanmao.test.framgent.Page04;
import com.wanmao.test.service.ProjectService;
import com.wanmao.test.service.ToolShowDemo;
import com.wanmao.test.util.StaticUtil;
import com.wanmao.test.util.SysApplication;

import java.util.HashMap;
import java.util.Map;

import nari.mip.core.MipConstant;
import nari.mip.core.Platform;

public class MainActivity extends BaseActivity {
    private Fragment homePageFinstFramgent;
    private Fragment networkGameFragment;
    private Fragment webGameFragment;
    private Fragment personalFragment;


    private ImageView img_bottom_01, img_bottom_02,  img_bottom_04;
    private TextView tv_bottom_01, tv_bottom_02,  tv_bottom_04;
    private LinearLayout layout_bottom_01, layout_bottom_02,  layout_bottom_04;
    private FragmentManager fragmentManager;

    private TextView tv_title;
    private ImageView img_selcet;
    public static String istrue;
    private ProjectService service=new ProjectService(this);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SysApplication.getInstance().addActivity(this);
        try {
            istrue=Platform.getCurrent().getSSOService().getSSOInfo().getOnlineLogined();
        }catch (Exception e) {
            Toast.makeText(this,"错误：e",Toast.LENGTH_SHORT).show();
        }
        intenView();
        initData();

    }

    private void intenView() {
        StaticUtil.list_jd.add("规划可研");
        StaticUtil.list_jd.add("工程设计");
        StaticUtil.list_jd.add("设备采购");
        StaticUtil.list_jd.add("设备制造");
        StaticUtil.list_jd.add("设备验收");
        StaticUtil.list_jd.add("运输储存");
        StaticUtil.list_jd.add("安装调试");
        StaticUtil.list_jd.add("设备安装");
        StaticUtil.list_jd.add("设备调试");
        StaticUtil.list_jd.add("竣工验收");
        StaticUtil.list_jd.add("运维检修");
        StaticUtil.list_jd.add("退役报废");
        StaticUtil.list_jd.add("综合类");

        StaticUtil.list_zy.add("电能质量");
        StaticUtil.list_zy.add("电气设备性能");
        StaticUtil.list_zy.add("化学");
        StaticUtil.list_zy.add("电测");
        StaticUtil.list_zy.add("金属");
        StaticUtil.list_zy.add("热工");
        StaticUtil.list_zy.add("保护与控制");
        StaticUtil.list_zy.add("自动化");
        StaticUtil.list_zy.add("信息通信");
        StaticUtil.list_zy.add("节能");
        StaticUtil.list_zy.add("环境保护");
        StaticUtil.list_zy.add("水机");
        StaticUtil.list_zy.add("水工");

        registerReceiver(sessiontimeout_receiver, new IntentFilter(
                MipConstant.ACTION_SESSION_TIMEOUT));

        IntentFilter intentFt = new IntentFilter();
        intentFt.addAction(MipConstant.ACTION_PLATFORM_STOP);
        intentFt.addAction(MipConstant.ACTION_PLATFORM_LOGOUT);
        registerReceiver(stop_logout_broadcastReceiver, intentFt);

        registerReceiver(login_another_broadcastReceiver, new IntentFilter(
                MipConstant.ACTION_LOGIN_ANOTHER));

        registerReceiver(net_state_broadcastReceiver, new IntentFilter(
                MipConstant.ACTION_NET_STATE));
        if (istrue.equals("true")) {
            http();
        }else {

        }

        layout_bottom_01 = (LinearLayout) findViewById(R.id.layout_bottom_01);
        layout_bottom_02 = (LinearLayout) findViewById(R.id.layout_bottom_02);
//        layout_bottom_03 = (LinearLayout) findViewById(R.id.layout_bottom_03);
        layout_bottom_04 = (LinearLayout) findViewById(R.id.layout_bottom_04);
        layout_bottom_01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setTabSelection(0);
                img_selcet.setVisibility(View.GONE);
                tv_title.setText("任务管理");
            }
        });
        layout_bottom_02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setTabSelection(1);
                img_selcet.setVisibility(View.GONE);
                tv_title.setText("查询");

            }
        });

        layout_bottom_04.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setTabSelection(3);
                img_selcet.setVisibility(View.GONE);
                tv_title.setText("个人信息");
            }
        });

        img_bottom_01 = (ImageView) findViewById(R.id.img_bottom_01);
        img_bottom_02 = (ImageView) findViewById(R.id.img_bottom_02);

        img_bottom_04 = (ImageView) findViewById(R.id.img_bottom_04);

        tv_bottom_01 = (TextView) findViewById(R.id.tv_bottom_01);
        tv_bottom_02 = (TextView) findViewById(R.id.tv_bottom_02);

        tv_bottom_04 = (TextView) findViewById(R.id.tv_bottom_04);

        tv_title=(TextView) findViewById(R.id.tv_main_title);
        img_selcet = (ImageView) findViewById(R.id.img_main_select);
        img_selcet.setVisibility(View.VISIBLE);
    }


    private void http() {
        Map<String, String> map = new HashMap<String, String>();
        try {
            map.put("LOGINNAME", Platform.getCurrent().getMembership().getCurrentUser().getUserName());
            String response = ToolShowDemo.manageWebServices("GetUserInfo", map);
            JSONObject json = null;
            json = JSON.parseObject(response);
            int result = json.getIntValue("result");
            if (result == 0) {
                String content = json.getString("description");

            } else if (result == 1) {
                JSONArray value = json.getJSONArray("resultValue");
                JSONObject obj = value.getJSONObject(0);
                StaticUtil.ISC_ID = obj.getString("ISC_ID");
                StaticUtil.RYMC = obj.getString("RYMC");
                StaticUtil.RYZY = obj.getString("RYZY");
                StaticUtil.DEPTNAME = obj.getString("DEPTNAME");
            }
        } catch (Exception e) {

        }
    }

    private void initData() {
        fragmentManager = getFragmentManager();
        setTabSelection(0);
        img_selcet.setVisibility(View.GONE);
        tv_title.setText("任务管理");
    }



    private void setTabSelection(int index) {
        clearSelection(); // 清空当前选中状态
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        hideFragments(transaction); // 隐藏所有Fragment

        switch (index) {
            case 0:
                img_bottom_01.setImageResource(R.mipmap.btn_renwu_true);
                tv_bottom_01.setTextColor(Color.parseColor("#5a77e5"));

                if (homePageFinstFramgent == null) {
                    homePageFinstFramgent = new Framgent_Test_Task();
                    transaction.add(R.id.main_content_frameLayout, homePageFinstFramgent);
                } else {
                    transaction.show(homePageFinstFramgent);
                }
                break;
            case 1:
                img_bottom_02.setImageResource(R.mipmap.btn_zhidu_true);
                tv_bottom_02.setTextColor(Color.parseColor("#5a77e5"));

                if (networkGameFragment == null) {
                    networkGameFragment = new Framgent_Test_Search();
                    transaction.add(R.id.main_content_frameLayout, networkGameFragment);
                } else {
                    transaction.show(networkGameFragment);
                }
                break;

            case 3:
                img_bottom_04.setImageResource(R.mipmap.btn_wode_true);
                tv_bottom_04.setTextColor(Color.parseColor("#5a77e5"));

                if (personalFragment == null) {
                    personalFragment = new Page04();
                    transaction.add(R.id.main_content_frameLayout, personalFragment);
                } else {
                    transaction.show(personalFragment);
                }
                break;


        }

        transaction.commit();

    }


    private void clearSelection() {
        img_bottom_01.setImageResource(R.mipmap.btn_renwu_false);
        img_bottom_02.setImageResource(R.mipmap.btn_zhidu_false);

        img_bottom_04.setImageResource(R.mipmap.btn_wode_false);

        tv_bottom_01.setTextColor(Color.parseColor("#b3b3b3"));
        tv_bottom_02.setTextColor(Color.parseColor("#b3b3b3"));

        tv_bottom_04.setTextColor(Color.parseColor("#b3b3b3"));
    }


    private void hideFragments(FragmentTransaction transaction) {
        if (homePageFinstFramgent != null) {
            transaction.hide(homePageFinstFramgent);
        }
        if (networkGameFragment != null) {
            transaction.hide(networkGameFragment);
        }
        if (webGameFragment != null) {
            transaction.hide(webGameFragment);
        }
        if (personalFragment != null) {
            transaction.hide(personalFragment);
        }

    }

    private BroadcastReceiver net_state_broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();

            if (action.equals(MipConstant.ACTION_NET_STATE)) {

                boolean flag = intent.getBooleanExtra(
                        MipConstant.NET_CONNECTED_SUCCESSFUL, true);

                if (!flag) {


                    alert("当前网络连接不可用");
                } else {


                }
            }

        }
    };

    private BroadcastReceiver login_another_broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {


            String action = intent.getAction();

            if (action.equals(MipConstant.ACTION_LOGIN_ANOTHER)) {

                try {

                    Platform.getCurrent().getSSOService()
                            .execute(Platform.METHOD_LOGIN_ANOTHER, null);

                } catch (Exception e) {

                    e.printStackTrace();
                }

                Toast.makeText(MainActivity.this,
                        "该账号已经在另一台设备上登录,如果不是本人操作,则账号信息可能已泄露!",
                        Toast.LENGTH_LONG).show();


                Platform.getCurrent().close(
                        MainActivity.this.getApplicationContext());


                MainActivity.this.startActivity(new Intent(context,
                        LoginActivity.class));

            }

        }

    };

    /**
     * 广播接收器，接收平台会话超时广播
     */
    private BroadcastReceiver sessiontimeout_receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub

            // 回到当前登录界面
            MainActivity.this.finish();
            MainActivity.this.startActivity(new Intent(context,
                    LoginActivity.class));

        }

    };

    /**
     * 广播接收器接收平台退出或者注销广播
     */
    private BroadcastReceiver stop_logout_broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub

            String action = intent.getAction();

            if (action.equals(MipConstant.ACTION_PLATFORM_STOP)) {

                MainActivity.this.finish();
            }

            //此处要按照下面方式写
            if (action.equals(MipConstant.ACTION_PLATFORM_LOGOUT)) {

                // 关闭当前登录界面
                MainActivity.this.finish();

                String pkgName = intent.getExtras().getString("pkgName");

                if (Platform.getCurrent().getAppContext().getPackageName().equals(pkgName)) {
                    //启动登录界面
                    MainActivity.this.startActivity(new Intent(MainActivity.this,LoginActivity.class));
                }
            }

        }

    };


    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

        unregisterReceiver(login_another_broadcastReceiver);
        unregisterReceiver(sessiontimeout_receiver);
        unregisterReceiver(stop_logout_broadcastReceiver);
        unregisterReceiver(net_state_broadcastReceiver);
    }
}
